package com.levi.rabbitmq.task;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class TaskProducer {

    public static final String TASK_QUEUE_NAME = "task_hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置rabbitmq地址
        connectionFactory.setHost("192.168.177.129");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //建立连接
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();

        //声明队列             队列名称        是否持久化         是否独有          是否自动删除       参数
        channel.queueDeclare(TASK_QUEUE_NAME, false, false, false, null);
        String message = "";
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                //偶数带.   奇数不带.
                 message = "task_hello    "+i;
            }else {
                 message = "task_hello... "+i;
            }

            //发送消息

            //                        交换机     队列名称         额外配置          要发送的消息
            channel.basicPublish("", TASK_QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println("发送了消息: " + message);
        }
        //关闭连接
        channel.close();
        connection.close();
    }
}
